<template>
  <el-form ref="bannerAdd" :model="bannerDetail" label-width="120px" :rules="rules">
    <!-- 轮播图名称 -->
    <el-form-item label="轮播图名称" prop="nickname">
      <el-input v-model="bannerDetail.nickname" />
    </el-form-item>
    <!-- 轮播图图片 -->
    <el-form-item label="轮播图图片">
      <el-upload
        v-model:file-list="fileList"
        action="/api/upload"
        accept=".jpg,.gif,.png"
        multiple
        :on-success="uploadSuccess"
        list-type="picture-card"
      >
        <el-button type="primary">上传图片</el-button>
      </el-upload>
    </el-form-item>
    <!-- 轮播图状态 -->
    <el-form-item label="是否显示">
      <el-switch
        v-model="bannerDetail.enable"
        inline-prompt
        active-text="显示"
        inactive-text="隐藏"
      />
    </el-form-item>
    <!-- 上传时间 -->
    <el-form-item label="上传时间" prop="time">
      <el-input v-model="bannerDetail.time" />
    </el-form-item>

    <!-- 提交添加商品 -->
    <el-form-item>
      <el-button type="primary" @click="onSubmit(bannerAdd)">确认</el-button>
      <el-button>重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { addBannerMessage } from '@/api/banner'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
//验证规则
const rules = {
  nickname: [
    {
      required: true,
      message: '该字段必填'
    }
  ],
  time: [
    {
      required: true,
      message: '该字段必填'
    }
  ]
}

//获取bannerDetail的初始值
let bannerDetail = ref({
  nickname: '',
  thumb: '',
  enable: true,
  time: ''
})

//获取图片回显的初始值
const fileList = ref([])
const uploadSuccess = (res: any) => {
  if (res.code === 200) {
    bannerDetail.value.thumb = res.data.url
    ElMessage({
      type: 'success',
      message: '上传成功'
    })
  }
}

//提交表单
const router = useRouter()
const bannerAdd = ref(null)
const onSubmit = (bannerAdd: any) => {
  bannerAdd.validate().then(() => {
    addBannerMessage(bannerDetail).then((res) => {
      if (res.data.code === 200) {
        ElMessage({
          type: 'success',
          message: '增加成功',
          duration: 2000,
          onClose: () => {
            router.go(0)
          }
        })
      } else {
        ElMessage({
          type: 'error',
          message: '增加失败'
        })
      }
    })
  })
}
</script>

<style scoped></style>
